%% Random assignment of baseline & validation groups
function [hat_theta, hat_vartheta, rep_base_se2, rep_val_se2] = random_assignment(estimates, se, seed)

    rng(seed);
    
    % Initialization
    num_rows = size(estimates, 1);
    hat_vartheta = zeros(num_rows, 1);  
    hat_theta = cell(num_rows, 1);  % Use cell array to handle varying column lengths
    rep_val_se2 = zeros(num_rows, 1); 
    rep_base_se2 = cell(num_rows, 1);  % Cell array for varying lengths

    for i = 1:num_rows
        % Find the indices of non-NaN elements in the current row
        valid_estimates = estimates(i, ~isnan(estimates(i, :)));
        valid_se = se(i, ~isnan(se(i, :)));
        
        % Get the number of valid entries
        num_valid = length(valid_estimates);

        % Randomly select an index for each row among the valid entries
        random_idx = randi(num_valid);
        
        % Extract the selected estimate and se for the current row
        hat_vartheta(i) = valid_estimates(random_idx);  
        rep_val_se2(i) = valid_se(random_idx)^2;

        % Remove the selected element from the remaining valid estimates and se
        remaining_idx = setdiff(1:num_valid, random_idx);
        hat_theta{i} = valid_estimates(remaining_idx);
        rep_base_se2{i} = valid_se(remaining_idx).^2;
    end

end
